package pl.edu.agh.pros.internal.proxy.topic;

import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.ros.namespace.GraphName;
import org.ros.node.ConnectedNode;
import org.ros.node.topic.Publisher;

import pl.edu.agh.pros.conf.ProxyConfiguration;
import pl.edu.agh.pros.internal.proxy.AbstractProxyNode;
import pl.edu.agh.pros.internal.proxy.IMessageReceiver;
import pl.edu.agh.pros.internal.proxy.ProxyDispatcher;
import pl.edu.agh.pros.util.RosMessageUtils;

public class ProxyTopicReceiver extends AbstractProxyNode implements IMessageReceiver {

	private Publisher<org.ros.internal.message.Message> publisher;
	private MultiUserChat multiUserChat;

	public ProxyTopicReceiver(ProxyDispatcher proxyDispatcher, ProxyConfiguration proxyNodeConfiguration) {
		super(proxyDispatcher, proxyNodeConfiguration);
	}

	@Override
	public GraphName getDefaultNodeName() {
		return new GraphName("pros_core/proxyTopicReceiver"); //$NON-NLS-1$
	}

	@Override
	public void onStart(ConnectedNode node) {
		this.node = node;
		publisher = node.newPublisher(proxyNodeConfiguration.getName(), proxyNodeConfiguration.getType());
		multiUserChat = proxyDispatcher.joinMultiUserChat(this, proxyNodeConfiguration.getName());
	}

	@Override
	public void onMessage(Message message) {
		org.ros.internal.message.Message rosMessage = RosMessageUtils.deserializeMessage(message, node,
				proxyNodeConfiguration.getType());
		publisher.publish(rosMessage);
	}

	@Override
	public boolean isRunning() {
		return this.node != null;
	}

	@Override
	public void dispose() {
		if (multiUserChat != null && proxyDispatcher.isConnected() && multiUserChat.isJoined()) {
			try {
				multiUserChat.leave();
			} catch (Exception e) {
				// ignore
			}
		}
	}

}
